<template>
  <div class="login-page">
    <div class="back">
      <geek-icon @click.native="$router.push('/')" name="esay-close"></geek-icon>
    </div>
    <h3 class="title">账号登录</h3>
    <!-- 表单 -->
    <van-form class="form" ref="form">
      <van-field placeholder="请输入账号" v-model="form.username" name="mobile" :rules="rules.username"></van-field>
      <van-field placeholder="请输入密码" v-model="form.password" type="password" name="mobile" :rules="rules.password"></van-field>
      <van-field placeholder="请输入验证码" v-model="form.captchaCode" :rules="rules.captchaCode">
        <template #button>
          <van-image :src="form.captcha" @click="send()" class="t-captcha-img"></van-image>
        </template>
      </van-field>
    </van-form>
    <van-button @click="login()">登录</van-button>
  </div>
</template>
<script>
import { userLogin, image } from '@/api/index'
export default {
  name: 'LoginPage',
  data () {
    return {
      form: {
        // 图形验证码信息
        captcha: null,
        // 登录账号
        username: null,
        // 密码
        password: null,
        // 图形验证码
        captchaCode: '',
        uuid: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入登录用户名' }
        ],
        password: [
          { required: true, message: '请输入登录密码' }
        ],
        captchaCode: [
          { required: true, message: '请输入验证码' }
        ]
      }
    }
  },
  created () {
    // 获取图形验证码
    this.send()
  },
  methods: {
    async login () {
      // 校验
      await this.$refs.form.validate()
      // 登录
      const [err, res] = await userLogin({
        username: this.form.username,
        password: this.form.password,
        code: this.form.captchaCode,
        uuid: this.form.uuid
      })
      // 失败
      if (err) {
        this.form.captchaCode = ''
        this.send()
        return
      }
      // 成功
      this.$toast.success('登录成功')
      this.$store.commit('user/setToken', res.token)
      this.$router.push(this.$route.query.returnUrl || '/')
    },
    // 获取验证码.
    async send () {
      const [, res] = await image(this.form)
      this.form.captcha = 'data:image/gif;base64,' + res.img
      this.form.uuid = res.uuid
    }
  }
}
</script>
<style scoped lang="less">
.body {
  background: #ffffff !important;
}
.t-captcha-img {
  width: 102px;
  height: 44px;
  float: right;
}
.login-page {
  padding: 0 32px;
  .back {
    height: 60px;
    display: flex;
    align-items: center;
    .geek-icon {
      font-size: 20px;
      color: #ccc;
      position: relative;
      left: -15px;
    }
  }
  .title {
    font-size: 22px;
    line-height: 1;
    padding: 30px 0;
  }
  .van-cell {
    padding: 20px 0;
    &::after {
      left: 0;
      right: 0;
    }
  }
  .van-button {
    width: 100%;
    margin-top: 40px;
    height: 50px;
    color: #fff;
    font-size: 16px;
    border: none;
    background: linear-gradient(to right, #ff9999, #ffa179);
  }
}
</style>
